package com.example.gateway.route.predicate;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import javax.validation.constraints.NotEmpty;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

@Component
public class CustomRoutePredicateFactory extends AbstractRoutePredicateFactory<CustomRoutePredicateFactory.Config> {


    public CustomRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        System.out.println("定期刷新路由");
        /**
         * 每次匹配路由时，会调用该断言进行判断
         */
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                ServerHttpRequest request = serverWebExchange.getRequest();
                ServerHttpResponse response = serverWebExchange.getResponse();
                String hostName = request.getRemoteAddress().getHostName();
                System.out.println(config);
                System.out.println(hostName);
                if(hostName.equals("localhost") || hostName.equals("127.0.0.1")){
                    return true;
                }
                return false;
            }
        };
    }

    /**
     * 绑定Config接收配置文件中的映射字段
     * 比如：断言工厂类CustomRoutePredicateFactory
     * Arrays.asList("name"); 则配置文件中 Custom=name接收的值
     * Arrays.asList("name","regexp");则配置文件中 Custom=name接收的值,regexp接收的值
     */
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("name");
    }

    /**
     * 用于接收配置文件中配置的值
     * 前提先用shortcutFieldOrder进行字段绑定
     * 比如：断言工厂类CustomRoutePredicateFactory
     * 则配置文件中配置应该为 - Custom=xxxx
     * 则name接收到的值为xxx
     */
    @Validated
    public static class Config {
        @NotEmpty
        private String name;
        public Config(){
        }
        public Config(String name) {
            this.name = name;

        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Config{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }
}
